package com.xhixm.chatbot.domain.ai.service;

import com.alibaba.fastjson.JSON;
import com.xhixm.chatbot.domain.ai.IOpenAI;
import com.xhixm.chatbot.domain.ai.model.aggregates.AIAnswer;
import com.xhixm.chatbot.domain.ai.model.aggregates.MyAiAnswer;
import com.xhixm.chatbot.domain.ai.model.vo.Choices;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class OpenAi implements IOpenAI {

    private Logger logger = LoggerFactory.getLogger(OpenAi.class);

    @Value("${my-chatbot.openAiKey}")
    private String openAiKey;
    @Override
    public String doChatGPT(String question,long userId) throws IOException {

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost("https://api.openai-proxy.com/v1/chat/completions");
        httpPost.setHeader("Content-Type","application/json");
        httpPost.setHeader("Authorization","Bearer "+openAiKey);

        /*UUID uuid = UUID.randomUUID();
        String id = uuid.toString();*/
        //代理服务
        String paramJson = "{\n" +
                "    \"apiKey\": \""+openAiKey+"\",\n" +
                "    \"sessionId\": \""+userId+"\",\n" +
                "    \"content\": \""+ question  +"\"\n" +
                "}";

        StringEntity stringEntity = new StringEntity(paramJson, ContentType.create("text/json", "UTF-8"));
        httpPost.setEntity(stringEntity);

        CloseableHttpResponse execute = httpClient.execute(httpPost);
        if (execute.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            String res = EntityUtils.toString(execute.getEntity());
            MyAiAnswer myAiAnswer = JSON.parseObject(res, MyAiAnswer.class);
            return myAiAnswer.getData();
        }else {
            throw new RuntimeException("api.openai.com Err Code is"+execute.getStatusLine().getStatusCode());
        }

    }
}
